﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Entities.Users;
using DotNetNuke.Modules.PowerShell.Args;
using DotNetNuke.Services.Localization;

namespace DotNetNuke.Modules.PowerShell.Contexts
{
	public class LocaleContext : BaseContext
	{
		public override void Process(IContextArgs args)
		{
			base.Process(args);

			if (IsValid)
			{
				var arg = args.Arguments;

				string locale = arg.ContainsKey("l") ? arg["l"] : string.Empty;

				switch (args.Action)
				{
					case "add":
						if (string.IsNullOrEmpty(locale))
						{
							AddResult("Please input the locale id which need to add");
						}
						else
						{
							AddLocale(locale);
						}
						break;
					default:
						AddResult("No Action");
						break;
				}
			}
		}

		private void AddLocale(string localeId)
		{
			var _language = LocaleController.Instance.GetLocale(localeId);

			if (UserController.GetCurrentUserInfo().IsSuperUser)
			{
				if (_language == null)
				{
					_language = new Locale();
					_language.Code = localeId;
				}
				//fix code up-lower case
				_language.Code = CultureInfo.CreateSpecificCulture(_language.Code).Name;
				_language.Fallback = CurrentPortalSettings.DefaultLanguage;
				_language.Text = CultureInfo.CreateSpecificCulture(_language.Code).NativeName;
				Localization.SaveLanguage(_language);
			}

			if (!IsLanguageEnabled(localeId))
			{
				//Add language to portal
				Localization.AddLanguageToPortal(CurrentPortalSettings.PortalId, _language.LanguageId, true);
			}

			string roles = Null.NullString;
			
			roles = string.Format("Administrators;{0}", string.Format("Translator ({0})", _language.Code));

			PortalController.UpdatePortalSetting(CurrentPortalSettings.PortalId, string.Format("DefaultTranslatorRoles-{0}", _language.Code), roles);

			var tabCtrl = new TabController();
			TabCollection tabs = tabCtrl.GetTabsByPortal(CurrentPortalSettings.PortalId).WithCulture(_language.Code, false);
			if (CurrentPortalSettings.ContentLocalizationEnabled && tabs.Count == 0)
			{
				//Create Localized Pages
				foreach (TabInfo t in tabCtrl.GetCultureTabList(CurrentPortalSettings.PortalId))
				{
					tabCtrl.CreateLocalizedCopy(t, _language);
				}

				var portalCtl = new PortalController();
				portalCtl.MapLocalizedSpecialPages(CurrentPortalSettings.PortalId, _language.Code);
			}

			AddResult("Add Language {0} successful", localeId);
		}

		private bool IsLanguageEnabled(string Code)
		{
			Locale enabledLanguage = null;
			return LocaleController.Instance.GetLocales(CurrentPortalSettings.PortalId).TryGetValue(Code, out enabledLanguage);
		}

		public override string Help
		{
			get { return "Locale Helper"; }
		}
	}
}